package lew.bing.tom;

import groovy.lang.Script;

import javax.servlet.ServletContext;
import java.io.File;

public class DefaultScriptProvider implements ScriptProvider{

    private InitGroovyScripts initGroovyScripts;
    private String rootPath;

    private boolean inited = false;

    public DefaultScriptProvider(String rootPath) {
        this.rootPath = rootPath;
        initGroovyScripts = new InitGroovyScripts(rootPath);
        initGroovyScripts.init();
    }

    public void init(ServletContext servletContext) {
        initGroovyScripts.afterInit(servletContext);
        inited = true;
    }


    @Override
    public Object getScript(String name) {
        final File file = new File(rootPath, name);
        if (file.exists() && file.isFile()) {
            // 注意不要为类注入参数，不然会出现线程安全问题
            // 最好的办法是直接参数传入
            return initGroovyScripts.loadScript(name);
        }
        return null;
    }

    @Override
    public boolean inited() {
        return inited = true;
    }
}
